package com.example.coursehub.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.List;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // 1. 禁用 CSRF 保护
        http.csrf(AbstractHttpConfigurer::disable);

        // 2. 配置 CORS 跨域支持
        http.cors(cors -> cors.configurationSource(corsConfigurationSource()));

        // 3. 开放所有请求权限（包括认证授权）
        http.authorizeHttpRequests(auth -> auth
                .anyRequest().permitAll() // 允许所有请求
        );

        return http.build();
    }

    // CORS 配置（允许所有来源）
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();

        // 允许所有来源
        configuration.setAllowedOriginPatterns(List.of("*"));

        // 允许所有HTTP方法
        configuration.setAllowedMethods(Arrays.asList(
                "GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"
        ));

        // 允许所有HTTP头
        configuration.setAllowedHeaders(List.of("*"));

        // 允许凭据（cookies）
        configuration.setAllowCredentials(true);

        // 设置预检请求缓存时间（1小时）
        configuration.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);

        return source;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}